﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SystemScanner.ClientServices;
using System.Reflection;
using System.DirectoryServices.ActiveDirectory;

namespace SystemScanner.Console
{
	class Program
	{
		static int Main(string[] args)
		{
			try
			{
				LogScanForLocalComputer(global::System.Console.Out);
				return 0;
			}
			catch (Exception ex)
			{
				global::System.Console.Error.WriteLine(ex.ToString());
				return -1;
			}
		}

		public static void LogScanForLocalComputer(System.IO.TextWriter logger)
		{
			logger.WriteLine("Starting system scan...");

			var computer = new Data.Computer
				{
					DomainName = Domain.GetComputerDomain().Name,
					Hostname = Environment.MachineName,
					Sid = ""
				};

			var versionInfo = new StringBuilder();
			var ava = System.Reflection.Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyVersionAttribute), true).FirstOrDefault() as AssemblyVersionAttribute;
			var fva = System.Reflection.Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyFileVersionAttribute), true).FirstOrDefault() as AssemblyFileVersionAttribute;
			if (ava != null && ava.Version.Length > 0)
			{
				versionInfo.AppendFormat("v:{0}", ava.Version);
			}
			if (fva != null && fva.Version.Length > 0)
			{
				if (versionInfo.Length > 0)
				{
					versionInfo.AppendFormat("/");
				}
				versionInfo.AppendFormat("fv:{0}", fva.Version);
			}

			var newScan = new SystemScanner.Data.Scan
			{
				Performed = DateTimeOffset.Now,
				ScannerVersion = versionInfo.ToString()
			};
			logger.WriteLine("   Retrieving hotfix information...");
			InstalledHotfixService.AddHotfixesToScan(newScan);
			logger.WriteLine("   Retrieving service information...");
			InstalledServicesService.AddServicesToScan(newScan);
			logger.WriteLine("   Retrieving Software information...");
			InstalledSoftwareService.AddSoftwareToScan(newScan);
			logger.WriteLine("   Retrieving OS Component information...");
			InstalledWindowsComponentsService.AddWindowsComponentsToScan(newScan);

			logger.WriteLine("   Saving to DB...");

			using (ScanLoggingService.ScanServiceClient client = new ScanLoggingService.ScanServiceClient())
			{
				client.ProcessScan(computer, newScan);
			}
			logger.WriteLine("Completed successfully.");
		}

	}
}